//
//  ShopController.m
//  RentTable
//
//  Created by xchuan xchuan on 2024/12/1.
//

#import "ShopController.h"
#import "ShopSuggView.h"
#import "ShopEmptyView.h"
#import "ShopTabCell.h"
#import "ShopBottomView.h"
#import "HomeTableDetailController.h"
#import "HomeConfirmOrderController.h"

#define ContentHeight 917  * scaleH

@interface ShopController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIScrollView *contentScollView;

@property (nonatomic, strong) ShopEmptyView *shopEmptyView;
@property (nonatomic, strong) ShopSuggView *shopSuggestView;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<RentModel *> *orderItem;

@property (nonatomic, strong) ShopBottomView *shopBottomView;

@property (nonatomic, assign) NSInteger priceSum;
@property (nonatomic, assign) BOOL allSelect;

@property (nonatomic, strong) NSMutableArray<RentModel *> *selectItem;

@property (nonatomic, strong) RentModel *selectRentModel;

@end

@implementation ShopController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.allSelect = false;
    self.priceSum = 0;
    self.orderItem = @[].mutableCopy;
    self.selectItem = @[].mutableCopy;
    NSArray<RentModel *>* item = [[RentManager sharedManager] getAllRentModelsWithCartTrue];
    if (item) {
        [self.orderItem addObjectsFromArray:item];
    }
    [self setUI];
    
    [self loadBackArrow];
    [self loadTitle:@"购物车"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.orderItem = @[].mutableCopy;
    NSArray<RentModel *>* item = [[RentManager sharedManager] getAllRentModelsWithCartTrue];
    if (item) {
        [self.orderItem addObjectsFromArray:item];
    }
    
    if (self.orderItem.count > 0) {
        if (!self.tableView) {
            [self loadTableView];
        }
        if (self.shopEmptyView) {
            [self.shopEmptyView setHidden:true];
        }
        [self updateShopConstarint];
        [self.tableView setHidden:false];
        [self.tableView reloadData];
    }else {
        if (!self.shopEmptyView) {
            [self loadEmptyView];
        }
        if (self.tableView) {
            [self.tableView setHidden:true];
        }
    }
}

- (void)setUI {
    
    CGFloat contentHeight = ContentHeight;
    self.contentScollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, spDeviceWidth, spDeviceHeight - 93 * scaleH)];
    [self.contentScollView setUserInteractionEnabled:true];
    self.contentScollView.contentSize = CGSizeMake(spDeviceWidth, contentHeight);
    self.contentScollView.showsHorizontalScrollIndicator = NO;
    self.contentScollView.showsVerticalScrollIndicator = NO;
    self.contentScollView.contentInset = UIEdgeInsetsZero;
    self.contentScollView.backgroundColor = myRGBHex(0xF8F8F8);
    self.contentScollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self.view addSubview:self.contentScollView];
    
    if (self.orderItem.count > 0) {
        [self loadTableView];
    }else {
        [self loadEmptyView];
    }
    
    [self loadSuggestView];
    
    [self loadBottomView];
}

- (void)updateShopView {
    NSArray<RentModel *>* item = [[RentManager sharedManager] getAllRentModelsWithCartTrue];
    if (item) {
        [self.orderItem addObjectsFromArray:item];
    }
    if (self.orderItem.count <= 0) {
        if (self.tableView) {
            [self.tableView setHidden:true];
        }
        if (!self.shopEmptyView) {
            [self loadEmptyView];
        }
        [self.shopEmptyView setHidden:false];
        
        [self.shopSuggestView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(spDeviceWidth);
            make.top.mas_equalTo(429 * scaleH);
            make.height.mas_equalTo(ContentHeight - 429 * scaleH);
        }];
    }else {
        [self.tableView setHidden:false];
        if (self.shopEmptyView) {
            [self.shopEmptyView setHidden:true];
        }
    }
}

- (void)loadEmptyView {
    self.shopEmptyView = [ShopEmptyView new];
    [self.contentScollView addSubview:self.shopEmptyView];
    [self.shopEmptyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.width.mas_equalTo(spDeviceWidth);
        make.height.mas_equalTo(420 * scaleH);
    }];
}

- (void)loadSuggestView {
    self.shopSuggestView = [ShopSuggView new];
    [self.contentScollView addSubview:self.shopSuggestView];
    [self.shopSuggestView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(spDeviceWidth);
        make.top.mas_equalTo(429 * scaleH);
        make.height.mas_equalTo(ContentHeight - 429 * scaleH);
    }];
    
    QLWEAKSELF
    self.shopSuggestView.orderSelect = ^(RentModel * _Nonnull rentModel) {
        HomeTableDetailController *vc = [HomeTableDetailController new];
        vc.rentModel = rentModel;
        vc.hidesBottomBarWhenPushed = true;
        [weakSelf.navigationController pushViewController:vc animated:true];
    };
}

- (void)loadTableView {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 10, 0);
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.scrollEnabled = false;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.tableView registerClass:[ShopTabCell class] forCellReuseIdentifier:@"ShopTabCell"];
    
    [self.contentScollView addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(16);
        make.trailing.mas_equalTo(-16);
        make.top.mas_equalTo(104 * scaleH);
        make.height.mas_equalTo(200);
        make.width.mas_equalTo(spDeviceWidth - 32);
    }];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 96 * scaleH)];
    footerView.backgroundColor = [UIColor clearColor];
    UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 66 * scaleH, footerView.frame.size.width, 20 * scaleH)];
    footerLabel.text = @"已经到底啦～";
    footerLabel.textAlignment = NSTextAlignmentCenter;
    footerLabel.font = [UIFont pingFangSCRegularWithSize:14];
    footerLabel.textColor = myRGBHex(0x666666);
    [footerView addSubview:footerLabel];
    
    self.tableView.tableFooterView = footerView;
    
    [self.tableView reloadData];
    
    [self updateShopConstarint];
}

- (void)loadBottomView {
    self.shopBottomView = [ShopBottomView new];
    [self.view addSubview:self.shopBottomView];
    [self.shopBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.bottom.trailing.mas_equalTo(0);
        make.height.mas_equalTo(93 * scaleH);
    }];
    
    QLWEAKSELF
    self.shopBottomView.shopAllSelect = ^(BOOL cal) {
        if (cal) {
            for (RentModel *rentModel in weakSelf.orderItem) {
                NSInteger price = rentModel.rentPrice * rentModel.rentPeriod * rentModel.rentCount * 30;
                weakSelf.priceSum += price;
            }
        }else {
            weakSelf.priceSum = 0;
        }
        
        [weakSelf.shopBottomView updateBottomView:weakSelf.priceSum];
        weakSelf.allSelect = cal;
        [weakSelf.tableView reloadData];
        
        weakSelf.selectItem = @[].mutableCopy;
        [weakSelf.selectItem addObjectsFromArray:weakSelf.orderItem];
    };
    
    self.shopBottomView.shopComplete = ^{
        HomeConfirmOrderController *vc = [HomeConfirmOrderController new];
        vc.rentModel = weakSelf.selectRentModel;
        vc.hidesBottomBarWhenPushed = true;
        [weakSelf.navigationController pushViewController:vc animated:true];
    };
    
    [self.shopBottomView updateAllTitle:self.orderItem.count];
}

- (void)updateShopConstarint {
    CGFloat tabHeight = [self tableViewHeight];
    CGFloat contentHeight = tabHeight +  580 * scaleH;
    
    
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(16);
        make.trailing.mas_equalTo(-16);
        make.top.mas_equalTo(104 * scaleH);
        make.height.mas_equalTo(tabHeight);
        make.width.mas_equalTo(spDeviceWidth - 32);
    }];
    
    [self.shopSuggestView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(spDeviceWidth);
        make.top.mas_equalTo(tabHeight + 130 * scaleH);
        make.height.mas_equalTo(contentHeight - 429 * scaleH);
    }];
    
    [self.view layoutIfNeeded];
    self.contentScollView.contentSize = CGSizeMake(spDeviceWidth, contentHeight);
}

- (CGFloat)tableViewHeight {
    NSInteger numberOfRows = self.orderItem.count;
    
    CGFloat rowHeight = 150 * scaleH;
    CGFloat cellSpacing = 16 * scaleH;
    CGFloat footerHeight = 96 * scaleH;
    CGFloat totalHeight = (numberOfRows * rowHeight) + ((numberOfRows - 1) * cellSpacing) + footerHeight;
    
    return totalHeight;
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.orderItem.count;
}

- (__kindof UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ShopTabCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShopTabCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    RentModel *model = self.orderItem[indexPath.row];
    cell.rentModel = model;
    cell.allSelect = self.allSelect;
    
    if (model.rentId == self.selectRentModel.rentId) {
        cell.shopSelectButton.selected = true;
    }else {
        cell.shopSelectButton.selected = false;
    }
    
    QLWEAKSELF
    cell.deleteBlock = ^(RentModel * _Nonnull rentModel) {
        [weakSelf.orderItem removeObjectAtIndex:indexPath.row];
        rentModel.rentCart = false;
        [[RentManager sharedManager] updateRentModel:rentModel];
        [weakSelf.tableView reloadData];
        
        NSInteger price = rentModel.rentPrice * rentModel.rentPeriod * rentModel.rentCount * 30;
        weakSelf.priceSum -= price;
        if (weakSelf.priceSum < 0) {
            weakSelf.priceSum = 0;
        }
        [weakSelf.shopBottomView updateBottomView:weakSelf.priceSum];
        [self.shopBottomView updateAllTitle:self.orderItem.count];
        
        [weakSelf toggleSelectItemByRentModel:rentModel operat:true];
        [weakSelf updateShopView];
    };
    
    cell.countChanged = ^(RentModel * _Nonnull rentModel, NSInteger count, BOOL cal) {
        NSInteger price = rentModel.rentPrice * rentModel.rentPeriod * (count - rentModel.rentCount) * 30;
        rentModel.rentCount = count;
        if (cal) {
            weakSelf.priceSum += price;
        }else {
            NSInteger price = rentModel.rentPrice * rentModel.rentPeriod * rentModel.rentCount * 30;
            rentModel.rentCount = 1;
            weakSelf.priceSum -= price;
            if (weakSelf.priceSum < 0) {
                weakSelf.priceSum = 0;
            }
        }
        [weakSelf.shopBottomView updateBottomView:weakSelf.priceSum];
    };
    
    cell.selectBlock = ^(RentModel * _Nonnull rentModel, BOOL cal) {
        weakSelf.priceSum = 0;
        NSInteger price = rentModel.rentPrice * rentModel.rentPeriod * rentModel.rentCount * 30;
        [weakSelf toggleSelectItemByRentModel:rentModel operat:!cal];
        if (cal) {
            weakSelf.priceSum += price;
        }else {
            weakSelf.priceSum -= price;
            if (weakSelf.priceSum < 0) {
                weakSelf.priceSum = 0;
            }
        }
        [weakSelf.shopBottomView updateBottomView:weakSelf.priceSum];
        weakSelf.selectRentModel = rentModel;
        [weakSelf.tableView reloadData];
    };
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"Selected row at index: %ld", (long)indexPath.row);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 155.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 96 * scaleH;
}

- (void)toggleSelectItemByRentModel:(RentModel *)rentModel operat:(BOOL)operat {
    RentModel *existingModel = nil;
    for (RentModel *model in self.selectItem) {
        if (model.rentId == rentModel.rentId) {
            existingModel = model;
            break;
        }
    }

    if (operat) {  // 删除操作
        if (existingModel) {
            [self.selectItem removeObject:existingModel];
        }
    } else {  // 添加操作
        if (!existingModel) {
            rentModel.rentBuyId = [NSString randomNumberStringWithLength:4].integerValue;
            [self.selectItem addObject:rentModel];
        }
    }
}



@end
